package com.itlong.cloud.intercept;

import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.controller.SmartCardDemoController;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.user.smartcard.ISmartCardUserInfoServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * C#管理中心登录拦截器.
 */
@Aspect
@Component
public class CManagementLoginIntercept {

    private static Logger LOG = LoggerFactory.getLogger(SmartCardDemoController.class);

    @Autowired
    ISmartCardUserInfoServiceClient iSmartCardUserInfoServiceClient;

 // 定义一个切入点
    @Pointcut("execution(* com.itlong.cloud.controller.SmartCardFaceController.*(..)) && !@annotation(com.itlong.cloud.annotation.UnAuthAccessRequired)")
    public void excudeService(){}

    @Around("excudeService()")
    public Object twiceAsOld(ProceedingJoinPoint thisJoinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //String[] interceptMethod= StringHandlerUtil.splitString(dontIntercept);
        String uri = request.getRequestURI();
        System.out.println (String.format("【%s】请求路由:%s，客户端地址：%s", DateUtil.fomatDate1(new Date()),
                uri, HttpProtocolUtil.getIpAddr(request)));
        // JSON.toJSONString(request.getParameterMap()

        //拿到token
        String token=request.getParameter("token");
        if(StringUtils.isNotBlank(token)){
            //解密token拿到用户信息
            String retrieveToken=iSmartCardUserInfoServiceClient.retrieve(token);
            if(retrieveToken==null){
                return new MessageVO(AppErrorCodeEnum.USER_TOKEN_ERROR.getErrorCode());
            }else{
                if(!token.equals(retrieveToken)){
                    return new MessageVO(AppErrorCodeEnum.MANAGEMENT_USER_TOKEN_ERROR.getErrorCode());
                }else{
                    return thisJoinPoint.proceed();
                }
            }
        }else{
            return new MessageVO(OperateErrorCodeEnum.USER_TOKEN_ERROR.getErrorCode());
        }
    }
}
